/*
 * Project: BooEditor
 * Author:  Johannes Kuhaupt
 * Last Change:
 *    by:   $Author: $
 *    date: $Date:   $
 * Copyright (c): Johannes Kuhaupt
 * Licence: Creative Commons CC BY-NC-SA 3.0
 */
package control;

import java.io.*;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Johannes Kuhaupt
 */
public class SettingsManager {
    
   private static Properties tempSettings = new Properties();

    private static boolean readonlyMode = false;
    private static boolean personalConfigInUse = false;

    private static final String personalPath = System.getProperty("user.home") + File.separator + ".LejosEditor" + File.separator + "LejosEditor.conf";
    private static final String globalPath = System.getProperty("user.dir") + "/settings/LejosEditor.conf";

    public static boolean isReadOnly() {
        return readonlyMode;
    }

    public static boolean isPersonalConfigInUse() {
        return personalConfigInUse;
    }

    public static void setReadonly(boolean pReadOnly) {
        readonlyMode = pReadOnly;
    }

    public static boolean isPersonalConfigFileReadable() {
        boolean success = false;
        try {
            File file = new File(personalPath);

            if (file.exists()) {
                if (file.canRead()) {
                    success = true;
                }
            }

        } catch (Exception ex) {
            System.err.println("Exception Catched: isPersonalConfigFileReadable" + "\n" + ex.toString());
            success = false;
        }

        return success;
    }

    public static boolean isPersonalConfigFileWriteable() {
        boolean success = false;
        try {
            File file = new File(personalPath);

            if (file.exists()) {
                if (file.canRead() && file.canWrite()) {
                    personalConfigInUse = true;
                    success = true;
                }
            }

        } catch (Exception ex) {
            System.err.println("Exception Catched: isPersonalConfigFileWritable" + "\n" + ex.toString());
            success = false;
        }
        return success;
    }

    public static boolean isGlobalConfigFileReadable() {
        boolean success = false;
        try {
            File file = new File(globalPath);

            if (file.exists()) {
                if (file.canRead()) {
                    success = true;
                } 
            }
        } catch (Exception ex) {
            System.out.println("Exception Catched: isGlobalConfigFileReadable" + "\n" + ex.toString());
            success = false;
        }
        return success;
    }

    public static boolean isGlobalConfigFileWritable() {
        boolean success = false;
        try {
            File file = new File(globalPath);

            if (file.exists()) {
                if (file.canRead() && file.canWrite()) {
                    success = true;
                } 
            } 

        } catch (Exception ex) {
            System.out.println("Exception Catched: isGlobalConfigFileWritable" + "\n" + ex.toString());
            success = false;
        }
        
        return success;
    }

    public static void loadPersonalConfig() {
        Reader reader = null;
        try {
            reader = new FileReader(personalPath);
            tempSettings.load(reader);
        } catch (Exception ex) {
            System.out.println("Exception Catched: loadPersonalConfig" + "\n" + ex.toString());

        } finally {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }

    }

    public static void loadGlobalConfig() {
        Reader reader = null;
        try {
            reader = new FileReader(globalPath);
            tempSettings.load(reader);

        } catch (Exception ex) {
            System.out.println("Exception Catched: loadGlobalConfig" + "\n" + ex.toString());

        } finally {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }

    }

    public static void activateWriteToPersonalConfig() {
        personalConfigInUse = true;
    }

    public static void activateWriteToGlobalConfig() {
        personalConfigInUse = false;
    }

    public static void checkIfFileAndDirectoryIsCreatable(String path) throws IOException {
        File file = new File(path);
        if (file.getParentFile().mkdir()) {
            file.createNewFile();
        } else {
            throw new IOException("Failed to create directory " + file.getParent());
        }
    }

    public static boolean isGlobalConfigFileCreateable() {
        boolean b = false;
        try {
            checkIfFileAndDirectoryIsCreatable(globalPath);
            b = true;
        } catch (IOException ex) {
            System.out.println("Exception Catched: isGlobalConfigFileCreateable" + "\n" + ex.toString());
            b = false;
        }
        return b;
    }

    public static boolean isPersonalConfigFileCreateable() {
        boolean b = false;
        try {
            checkIfFileAndDirectoryIsCreatable(personalPath);
            b = true;
        } catch (IOException ex) {
            System.out.println("Exception Catched: isPersonalConfigFileCreateable" + "\n" + ex.toString());
            b = false;
        }
        return b;
    }

    

    /**
     * Checks the config file (syntactical correctness)
     *
     * @return
     */
    public static boolean hasRightConfigFileContent() {
        return true;
    }

    
    
    
    
    
    
    
    
    
    /**
     * Standard setting for first use (no config file created yet)
     * standard values for config file will be set
     */
    public static void createStandardSettings(){
        tempSettings.setProperty("PATH_TO_LEJOSCOMPILER", "");  
        tempSettings.setProperty("PATH_TO_LEJOSUPLOADER", "");
        tempSettings.setProperty("PATH_TO_JAREXTENSION", "");
        tempSettings.setProperty("LINENUMBERS", "true");
        tempSettings.setProperty("HIGHLIGHTACTIVELINE", "true");
        tempSettings.setProperty("SHOWSPACES", "false");
        tempSettings.setProperty("ANTIALIAS", "true");
        tempSettings.setProperty("FONTNAME", "Monospaced");
        tempSettings.setProperty("FONTSIZE", "13");
        tempSettings.setProperty("FONTSTYLE", "0");
        tempSettings.setProperty("FONTSIZEBIGSCREEN", "36");
        tempSettings.setProperty("SYNTAXHIGHLIGHTING", "true");
        tempSettings.setProperty("HIGHLIGHTINGTHEME", "default");
        tempSettings.setProperty("AUTOINDENTATION", "true");
        tempSettings.setProperty("AUTOCOMPLETION", "false");        
        tempSettings.setProperty("INDENTATIONBYTAB", "true");
        tempSettings.setProperty("TABSIZE", "4");        
        tempSettings.setProperty("FRAMEWIDTH", "800");
        tempSettings.setProperty("FRAMEHEIGHT", "500");
        tempSettings.setProperty("FRAMEPOSITIONX", "0");
        tempSettings.setProperty("FRAMEPOSITIONY", "0");
        tempSettings.setProperty("ShowToolbarRight", "true");
        
    }
    
    

    
   

    
    /**
     * Debug method. Prints all setting to screen.
     */
    public static void printSettings(){
        Enumeration e = tempSettings.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            System.out.println(key + " -- " + tempSettings.getProperty(key));
        }        
                
    }
    
    /**
     *
     * @param pKey
     * @return
     */
    public static String getStringSettingValue(String pKey){
        return tempSettings.getProperty(pKey);
        
    }
    
    /**
     *
     * @param pKey
     * @return theValue as String
     */
    public static boolean getBooleanSettingValue(String pKey){
        if(tempSettings.getProperty(pKey).equals("true")) return true;
        else{
            if(tempSettings.getProperty(pKey).equals("false")){ return false;}
            else {throw new IllegalArgumentException();}
        }       
        
    }
    
    /**
     *
     * @param pKey
     * @return theValue as int
     */
    public static int getIntSettingValue(String pKey){
        return Integer.parseInt(tempSettings.getProperty(pKey));
    }
    
    /**
     *
     */
    public static void checkProperties(){
        //vorhanden
        //schreibar
        //korrekt
    }
    
    /**
     * Update option item
     * @param pItem
     * @param pValue
     */
    public static void updateSettingsItem(String pItem, String pValue){
            tempSettings.setProperty(pItem, pValue);
    }

    /**
     * Write the user settings in the config file.
     *
     * @param toPersonalConfig
     */
    public static void writeSettingsToFile(boolean toPersonalConfig) {
        Writer writer = null;
        String path = globalPath;
        if (toPersonalConfig) {
            path = personalPath;
        }
        try {
            writer = new FileWriter(path);
            tempSettings.store(writer, null);

        } catch (Exception ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error,  writeSetttingsToFile failed mit " + toPersonalConfig + " " + ex.toString());
        } finally {
            try {
                writer.close();
            } catch (Exception e) {
            }

        }
    }


    
   
    
    
}
